package com.tiku.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tiku.common.ResultJson;
import com.tiku.entity.UserOrder;
import com.tiku.entity.UserOrderRelation;
import com.tiku.entity.UserPayTiku;
import com.tiku.mapper.UserOrderMapper;
import com.tiku.service.UserOrderRelationService;
import com.tiku.service.UserOrderService;
import com.tiku.service.UserPayTikuService;
import com.tiku.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/alipay")
@CrossOrigin("*")
public class AlipayController {
    @Value("${alipay.privateKey}")
    private String privateKey;
    @Value("${alipay.alipayPublicKey}")
    private String alipayPublicKey;
    @Value("${alipay.appId}")
    private String appId;

    @Autowired
    private UserOrderService userOrderService;

    @Autowired
    private UserPayTikuService userPayTikuService;

    @Autowired
    private UserOrderRelationService orderRelationService;

    @PostMapping("/pay")
    public ResultJson alipay(@RequestBody String order) throws AlipayApiException {
        String userId = ThreadLocalUtil.getThreadLocal();
        UserOrder userOrder = userOrderService.getBaseMapper().selectOne(new LambdaQueryWrapper<UserOrder>().eq(UserOrder::getOrderNumber, order).eq(UserOrder::getUserId,userId));
        if (Objects.isNull(userOrder)){
            return ResultJson.error("订单不存在");
        }
        if ("1".equals(userOrder.getOrderType())) {
            return ResultJson.error("订单已支付");
        }
        BigDecimal money = userOrder.getMoney();
        List<UserOrderRelation> list = orderRelationService.list(new LambdaQueryWrapper<UserOrderRelation>()
                .eq(UserOrderRelation::getOrderNumber, order));

        List<UserPayTiku> payTikuList = userPayTikuService.list(new LambdaQueryWrapper<UserPayTiku>()
                .eq(UserPayTiku::getUserId, userId));

        for (UserOrderRelation userOrderRelation : list) {
            String specid = userOrderRelation.getSpecid();
            // 使用 Stream API 查找 paySpecId 是否存在
            boolean isExist = payTikuList.stream()
                    .anyMatch(userPayTiku -> userPayTiku.getPaySpecId().equals(specid));

            // 输出结果
            if (isExist) {
                return ResultJson.error("该科目已购买！");
            }
        }

        AlipayConfig alipayConfig = new AlipayConfig();
        //沙盒网关地址
        alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
        alipayConfig.setAppId(appId);
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");

        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        //设置订单号
        model.setOutTradeNo(order);
        //设置支付金额
        model.setTotalAmount(money.toString());

        model.setSubject("才仕考");
        request.setBizModel(model);
        request.setNotifyUrl("http://34ts650316oz.vicp.fun/alipay_callback");
        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
        String orderStr = response.getBody();
        System.out.println(orderStr);
        if (response.isSuccess()) {
            System.out.println("调用成功");
            return ResultJson.success(orderStr);
        } else {
            return ResultJson.error("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
    }

}
